import { UpCircleOutlined } from "@ant-design/icons";

import React, { useRef, useEffect, useState } from "react";

const onMouseDown = (ref, draggable) => (e) => {
  //  记录鼠标距离可拖拽组件的上边距和左边距，使拖动更加准确，不记录的话鼠标每次点击组件，组件左上角就会跑到鼠标处
  draggable.dy = e.clientY - ref.current.offsetTop;
  draggable.dx = e.clientX - ref.current.offsetLeft;
  draggable.status = true;
};

const onMouseMove = (ref, draggable) => (e) => {
  if (draggable.status) {
    const div = ref.current;
    div.style.top = `${e.clientY - draggable.dy}px`;
    div.style.left = `${e.clientX - draggable.dx}px`;
  }
};

const onMouseUp = (draggable) => () => {
  draggable.status = false;
};

const draggable = {
  status: false,
  dy: 0,
  dx: 0,
};

const MyComponenet = (props) => {
  const ref = useRef(null);
  useEffect(() => {
    document.addEventListener("mousemove", onMouseMove(ref, draggable));
    document.addEventListener("mouseup", onMouseUp(draggable));
  }, []);
  return (
    <div
      ref={ref}
      style={{ position: "fixed", left: 200, top: 200 }}
      onMouseDown={onMouseDown(ref, draggable)}
    >
      <UpCircleOutlined rev />;
    </div>
  );
};

export default MyComponenet;
